/**
 * 菜单服务
 * 作者：GodMainCode
 * 创建时间：2024-01-17
 * 修改时间：2024-01-17
 * 修改人：GodMainCode
 */

import { Injectable } from '@nestjs/common';
import { Permission } from './entities/permission.entity';
import { PermissionType } from '../../interfaces/permission.interface';
import { MenuResponseDto } from './dto/menu-response.dto';

@Injectable()
export class MenuService {
  /**
   * 将权限转换为菜单树
   * @param permissions 权限列表
   * @returns MenuResponseDto[] 菜单树
   */
  transformToMenuTree(permissions: Permission[]): MenuResponseDto[] {
    // 过滤出目录和菜单类型的权限
    const menuPermissions = permissions.filter(
      p => p.type === PermissionType.DIRECTORY || p.type === PermissionType.MENU
    );

    // 转换为菜单格式
    const menus = menuPermissions.map(p => this.transformToMenu(p));

    // 构建树形结构
    return this.buildTree(menus);
  }

  /**
   * 将权限转换为菜单
   * @param permission 权限信息
   * @returns MenuResponseDto 菜单信息
   */
  private transformToMenu(permission: Permission): MenuResponseDto {
    return {
      id: permission.id,
      name: permission.code,
      path: permission.path || '',
      component: permission.component,
      parentId: permission.parent?.id,
      meta: {
        title: permission.name,
        icon: permission.icon,
        orderNo: permission.sort,
      },
    };
  }

  /**
   * 构建树形结构
   * @param menus 菜单列表
   * @param parentId 父级ID
   * @returns MenuResponseDto[] 菜单树
   */
  private buildTree(menus: MenuResponseDto[], parentId: number | null = null): MenuResponseDto[] {
    const tree: MenuResponseDto[] = [];

    menus.forEach(menu => {
      if (parentId === null && !menu.parentId) {
        const node = { ...menu };
        node.children = this.buildTree(menus, menu.id);
        tree.push(node);
      } else if (menu.parentId === parentId) {
        const node = { ...menu };
        node.children = this.buildTree(menus, menu.id);
        tree.push(node);
      }
    });

    return tree.sort((a, b) => (a.meta.orderNo || 0) - (b.meta.orderNo || 0));
  }
} 